package com.shadow.baiqun.delegate.room.goodsclassify;

import android.device.ScanDevice;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.receive.adapter.ItemName;
import com.shadow.baiqun.delegate.receive.adapter.PartCheckAdapter;
import com.shadow.baiqun.delegate.receive.partcheck.MatchDataConverter;
import com.shadow.baiqun.delegate.receive.partcheck.PartCheckDataConverter;
import com.shadow.baiqun.delegate.receive.partcheck.PartCheckEntity;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.progress.sweetalert.DialogLoader;
import com.shadow.ui.progress.sweetalert.IDialogClickListener;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;

/**
 * 货物归位流程
 */
public class GoodsClassifyDelegate extends RxShadowDelegate {
    private static final String PART_ID = "partId";
    private boolean isMine = false;
    private int mScanCount = 1;
    private int mCurrentPosition = -1;
    private ScanDevice mScanDevice;

    public static GoodsClassifyDelegate create(String partId) {
        final GoodsClassifyDelegate contentDelegate = new GoodsClassifyDelegate();
        final Bundle bundle = new Bundle();
        bundle.putString(PART_ID, partId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    private static final int PAGE_SIZE = 20;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    PartCheckAdapter mAdapter;
    private String mPartId;
    //正在请求
    private int mNextRequestPage = 1;
    private boolean isRequesting = false;
    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPartId = bundle.getString(PART_ID);
        }
        mScanDevice = new ScanDevice();
        //广播输出
        mScanDevice.setOutScanMode(0);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_part_check;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("零件数量核对");
        }
        mDialogLoader = new DialogLoader(getContext());
        mAdapter = new PartCheckAdapter(R.layout.item_part_check, null);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    int i = view.getId();
                    if (i == R.id.btn_scan) {
                        if (position != mCurrentPosition) {
                            //两次是一次完整
                            reset();
                        }
                        mCurrentPosition = position;
                        mDialogLoader.showProgressDialogWithCancel("正在扫描",
                                "请扫描" + (mScanCount == 1 ? "零件标签" : "库位标签")
                                , new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        stopScan();
                                    }
                                });
                        startScan();
                    }
                }
            }
        });
        mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mAdapter.getEmptyView() != null) {
            mAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isRequesting) {
                        mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
                        refresh();
                    }
                }
            });
        }
        mRecyclerView.setAdapter(mAdapter);
    }

    private void loadMore() {
        requestData(false);
    }

    private void requestData(final boolean isRefresh) {
        isRequesting = true;
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/turnbag/getStockCheckList")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        PartCheckDataConverter converter = new PartCheckDataConverter();
                        converter.setJsonData(response);
                        setData(isRefresh, converter.convert());
                        isRequesting = false;
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                    }
                })
                .params("taskid", mPartId)
                .params("pageNum", mNextRequestPage)
                .params("pageSize", PAGE_SIZE)
                .build()
                .unRestGet());
    }

    private void reset() {
        isMine = false;
        mScanCount = 1;
    }

    //刷新
    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    private void startScan() {
        mDialogLoader.changeText("正在扫描", "请扫描" + (mScanCount == 1 ? "零件标签" : "库位标签"));
        isMine = true;
        if (!mScanDevice.isScanOpened()) {
            mScanDevice.openScan();
        }
        mScanDevice.startScan();
    }

    private void stopScan() {
        reset();
        mScanDevice.stopScan();
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void scanEvent(ScanInfoEvent event) {
        if (isMine) {
            isMine = false;
            MultipleItemEntity entity = mAdapter.getItem(mCurrentPosition);
            if (entity != null) {
                String barCode = entity.getField(ItemName.ITEM_PART_CODE);
                if (mScanCount == 1) {
                    if (barCode == null || barCode.isEmpty()) {
                        mDialogLoader.stopProgressWithFailed("扫描失败!", "零件条码不匹配!");
                    } else {
                        if (!barCode.equals(event.mInfo)) {
                            mDialogLoader.stopProgressWithFailed("扫描失败!", "零件条码不匹配!");
                        } else {
                            ToastUtils.showToast(getContext(), "零件条码匹配成功!");
                            mDialogLoader.clearDialog();
                            mScanCount++;
                        }
                    }
                } else if (mScanCount == 2) {
                    postScanData(barCode, event.mInfo);
                    reset();
                }
            }
        }
    }

    private void postScanData(String barCode, String stationCode) {
        mDialogLoader.changeText("扫描完成", "正在提交...");
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/indoorTest/checkIsScan")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int status = jsonObject.getInteger("status");
                        String msg = jsonObject.getString("Msg");
                        if (status == 1) {
                            mDialogLoader.stopProgressWithSuccess(
                                    "提交成功", msg, new IDialogClickListener() {
                                        @Override
                                        public void onClick() {
                                            mDialogLoader.clearDialog();
                                            refresh();
                                        }
                                    });
                        } else {
                            mDialogLoader.stopProgressWithFailed("提交失败",
                                    msg);
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.clearDialog();
                        ToastUtils.showToast(getContext(), "匹配失败!");
                    }
                })
                .params("gcl", barCode)
                .params("dl", stationCode)
                .build()
                .unRestGet());
    }

    private void updateToServer(PartCheckEntity entity) {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/collectgoods/scanInUpdata")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (new ResultConverter().isSucceed(response)) {
                            mDialogLoader.clearDialog();
                            ToastUtils.showToast(getContext(), "更新成功!");
                            refresh();
                        } else {
                            mDialogLoader.stopProgressWithFailed("更新失败!", "数据更新失败!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.clearDialog();
                        ToastUtils.showToast(getContext(), "匹配失败!");
                    }
                })
                .params("num", entity.getStockNum())
                .params("depotid", entity.getStockDepotId())
                .params("stockid", entity.getStockId())
                .build()
                .unRestGet());
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }
}
